import {Component, OnInit, ViewChild} from '@angular/core';
import {LocalStorageService} from '../../../../lib/service/local-storage.service';
import {OrdinarySpellService} from '../ordinary-spell/ordinary-spell.service';
import {AliyunOssOutputUrl} from '../../../../../config/api';
import {ModalDirective} from 'ngx-bootstrap';
import * as moment from 'moment';

// 新建拼团
export class CreateSpell {
  applet_uuid: string;
  name: string;
  start_date: number;
  end_date: string;
  status: string;
  periods: number;
  description: string;
}

export class AddActivityGoods {
  activity_id: number;
  goods_id: number;
  goods_sku: string;
  type = 1;
  number: number;
  round = 0;
  sku_info;
  new_open_group = 0; // 是否新人开团  0不是 1是
  new_offer = 0; // 是否新人参团
  winners_number;
  free_scale; // 免单比例
  head_win = 0; // 是否团长中奖
}

// 编辑拼团
export class EditSpell {
  applet_uuid: string;
  id: number;
  name: string;
  start_date: number;
  end_date: string;
  status: string;
  periods: number;
  description: string;
}

// 编辑活动商品
export class EditGoods {
  id: number;
  activity_id: number;
  goods_id: number;
  type = 1;
  number: number;
  round = 100;
  sku_info;
  new_open_group; // 是否新人开团  0不是 1是
  new_offer; // 是否新人参团
  winners_number;
  free_scale;
  head_win;
}


@Component({
  selector: 'app-ordinary-spell',
  templateUrl: 'ordinary-spell.component.html',
  styleUrls: ['ordinary-spell.component.scss'],
  providers: [OrdinarySpellService, LocalStorageService]
})

export class OrdinarySpellComponent implements OnInit {

  curDate;
  status = '进行中';
  applet_uuid;
  aliyunOssOutputUrl;
  groupList;
  allGoodsNum;
  goodsList;
  // groupID = 0;  // 当前选中的分组ID
  checkedGood;
  editCheckedGoods;
  goodsSku = [];
  activity_price: number;  // 参团价格
  activityList = [];
  operateId: number;
  activityStatus: string;  // 活动状态
  createSpell = new CreateSpell();
  addActivityGoods = new AddActivityGoods();
  editSpell = new EditSpell();
  editGoods = new EditGoods();
  keyWordDlg;
  groupIdDlg = 0;
  isEditSpell = false;
  free_scale = 100;
  random_free = false;  // 是否随机免单

  loadingShow = true;
  canClick = true;
  type: string;
  message: string;
  isShow = false;
  totalItems: number;
  itemsPerPage = 12;
  currentPage = 1;
  totalItemsDlg: number;
  itemsPerPageDlg = 4;
  currentPageDlg = 1;

  @ViewChild('addGoodsModal') public addGoodsModal: ModalDirective;
  // @ViewChild('createSpellModal') public createSpellModal: ModalDirective;
  @ViewChild('editSpellModal') public editSpellModal: ModalDirective;
  @ViewChild('changeStatusModal') public changeStatusModal: ModalDirective;
  @ViewChild('delModal') public delModal: ModalDirective;

  constructor(private ordinarySpellService: OrdinarySpellService,
              private localStorageService: LocalStorageService) {
    this.aliyunOssOutputUrl = AliyunOssOutputUrl;
  }

  ngOnInit() {
    this.applet_uuid = this.localStorageService.getNowApplet().applet_uuid;
    this.getGroupList();
    this.getGoodsList(1);
    this.curDate = moment().format('YYYY-MM-DD');
    this.getActivityList(1, this.itemsPerPage, this.applet_uuid, this.status);
  }

  // 获取商品分组列表
  getGroupList() {
    this.ordinarySpellService.getGroupList(this.applet_uuid).subscribe(
      res => {
        this.groupList = res.data.data;
        // this.ordinarySpellService.getGoodsList(this.applet_uuid, 1, 999).subscribe(
        //   res1 => {
        //     this.allGoodsNum = res1.data.data.length;
        //   }
        // );
        // this.groupList.every((val, idx, array) => {
        //   this.ordinarySpellService.getGoodsList(this.applet_uuid, 1, 999, val.id).subscribe(
        //     res2 => {
        //       val.goodsNum = res2.data.data.length;
        //     }
        //   );
        //   return true;
        // });
      }
    );
  }

  // 获取商品列表
  getGoodsList(page: number, applet_goods_category_id?: number, status?: string, keyword?: string, order?: string) {
    // this.loadingShow = true;
    // this.currentPageDlg = null;
    this.ordinarySpellService.getGoodsList(this.applet_uuid, page, this.itemsPerPageDlg, applet_goods_category_id, status, keyword, order).subscribe(
      res => {
        if (res.code === 2000) {
          // setTimeout(
          //   () => {
          //     this.loadingShow = false;
          //   }, 500);
          this.goodsList = res.data.data;
          this.currentPageDlg = res.data.current_page;
          this.totalItemsDlg = res.data.total;
          const ids = [];
          this.goodsList.every((val, idx, array) => {
            ids.push(val.id);
            return true;
          });
          this.ordinarySpellService.getbindListAll(JSON.stringify(ids)).subscribe(
            res1 => {
              this.goodsList.every((val, idx, array) => {
                val.goods_category = [];
                res1.data.every((val1, idx1, array1) => {
                  if (val.id === val1.goods_id) {
                    val.goods_category.push({name: val1.name, id: val1.applet_goods_category_id});
                  }
                  return true;
                });
                return true;
              });
            }
          );
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 添加商品..弹框中的搜索与重置
  searchDlg() {
    this.currentPageDlg = 1;
    this.getGoodsList(1, this.groupIdDlg, '上架', this.keyWordDlg);
  }
  resetDlg() {
    this.keyWordDlg = '';
    this.groupIdDlg = 0;
    this.getGoodsList(1, this.groupIdDlg, '上架');
  }

  choseType(status) {
    this.status = status;
    this.isEditSpell = false;
    if (status !== '新建拼团') {
      this.getActivityList(1, this.itemsPerPage, this.applet_uuid, this.status);
    } else {
      this.checkedGood = '';
      this.goodsSku = [];
    }
  }

  getActivityList(page,
                  pageSize,
                  applet_uuid,
                  stage,
                  name?,
                  status?) {
    this.ordinarySpellService.getActivityList(page, pageSize, applet_uuid, stage, name, status).subscribe(
      res => {
        if (res.code === 2000) {
          this.currentPage = res.data.current_page;
          this.totalItems = res.data.total;
          this.activityList = res.data.data;
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 选择分组之后
  // chooseGroup(id: number) {
  //   this.goodsList = [];
  //   this.currentPage = null;
  //   this.groupID = id;
  //   this.getGoodsList(1, id);
  // }

  pageChanged(event) {
    window.scrollTo(0, 0);
    this.getActivityList(event.page, this.itemsPerPage, this.applet_uuid, this.status);
  }
  dlgPageChanged(event) {
    this.getGoodsList(event.page, this.groupIdDlg, '上架', this.keyWordDlg);
  }

  // 选中商品选项
  checkedGoods(item) {
    if (this.status === '新建拼团') {
      this.checkedGood = item;
      this.addGoodsModal.hide();
      this.addActivityGoods.goods_id = item.id;
      this.addActivityGoods.goods_sku = item.norm_mode;
      this.ordinarySpellService.getGoodsSkuList(item.id).subscribe(
        res => {
          this.goodsSku = res.data.data;
          this.goodsSku.every((val, idx, array) => {
            val.selected = true;
            return true;
          });
        });
    } else {
      this.editCheckedGoods = item;
      this.addGoodsModal.hide();
      this.editGoods.goods_id = item.id;
      // this.editGoods.goods_sku = item.norm_mode;
      this.ordinarySpellService.getGoodsSkuList(item.id).subscribe(
        res => {
          this.goodsSku = res.data.data;
          this.goodsSku.every((val, idx, array) => {
            val.selected = true;
            return true;
          });
        });
    }

  }

  // 新建拼团
  // createSpellDialog(id, norm_mode) {
  //   this.addActivityGoods.goods_id = id;
  //   this.addActivityGoods.goods_sku = norm_mode;
  //   this.getGoodsSkuList(id);
  // }

  getGoodsSkuList(id) {
    this.ordinarySpellService.getGoodsSkuList(id).subscribe(
      res => {
        this.goodsSku = res.data.data;
        this.activity_price = this.goodsSku[0].price / 1000;
        this.goodsSku.every((val, idx, array) => {
          val.selected = true;
          return true;
        });
        // this.createSpellModal.show();
      });
  }

  // 选择团长必免
  checkedHead() {
    if (this.addActivityGoods.head_win === 0) {
      this.addActivityGoods.head_win = 1;
    } else {
      this.addActivityGoods.head_win = 0;
    }
  }

  // 提交新建拼团
  addOrdinarySpell() {
    if (!this.random_free) {
      delete this.addActivityGoods.winners_number;
      delete this.addActivityGoods.head_win;
      delete this.addActivityGoods.free_scale;
    } else {
      if (!!this.addActivityGoods.winners_number && !!this.free_scale) {
        this.addActivityGoods.free_scale = this.free_scale / 100;
      } else {
        this.type = 'info';
        this.isShow = true;
        this.message = '请填写随机免单信息';
        return;
      }
    }
    const sku_info = [];
    this.goodsSku.every((val, idx, array) => {
      if (!!val.selected) {
        sku_info.push({sku_id: val.id, name: val.name, number: val.in_stock, price: this.activity_price});
        return true;
      }
      return true;
    });
    if (!sku_info.length) {
      this.type = 'info';
      this.message = '请选择商品规格';
      this.isShow = true;
      return;
    } else {
      this.addActivityGoods.sku_info = JSON.stringify(sku_info);
    }
    this.canClick = false;
    this.createSpell.applet_uuid = this.applet_uuid;
    this.ordinarySpellService.postAddActivity(this.createSpell).subscribe(
      res => {
        this.canClick = true;
        if (res.code === 2000) {
          this.addActivityGoods.activity_id = res.data;
          this.addGoods();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 活动商品添加
  addGoods() {
    this.ordinarySpellService.postAddActivityGoods(this.addActivityGoods).subscribe(
      res => {
        if (res.code === 2000) {
          // this.createSpellModal.hide();
          this.type = 'success';
          this.message = '活动添加成功';
          this.isShow = true;
          if (this.createSpell.start_date > this.curDate) {
            this.status = '未开始';
          } else {
            this.status = '进行中';
          }
          this.getActivityList(1, this.itemsPerPage, this.applet_uuid, this.status);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 编辑拼团
  editSpellDialog(data) {
    this.operateId = data.id;
    // 获取活动详情
    this.ordinarySpellService.getGoodsSkuList(data.activity_goods[0].goods_id).subscribe(
      res => {
        this.goodsSku = res.data.data;
        this.ordinarySpellService.getActivityInfo(this.applet_uuid, data.id).subscribe(
          rs => {
            const data = rs.data;
            this.editSpell.applet_uuid = data.applet_uuid;
            this.editSpell.id = data.id;
            this.editSpell.name = data.name;
            this.editSpell.start_date = data.start_date;
            this.editSpell.end_date = data.end_date;
            this.editSpell.status = data.status;
            this.editSpell.description = data.description;
            this.editSpell.periods = data.periods;
            this.editGoods.id = data.activity_goods[0].id;
            this.editGoods.activity_id = data.activity_goods[0].activity_id;
            this.editGoods.goods_id = data.activity_goods[0].goods_id;
            this.editGoods.number = data.activity_goods[0].number;
            this.editGoods.round = data.activity_goods[0].round;
            this.editGoods.new_open_group = data.activity_goods[0].new_open_group;
            this.editGoods.new_offer = data.activity_goods[0].new_offer;
            if (!!data.activity_goods[0].winners_number) {
              this.editGoods.winners_number = data.activity_goods[0].winners_number;
              this.editGoods.head_win = data.activity_goods[0].head_win;
              this.editGoods.free_scale = data.activity_goods[0].free_scale;
            } else {
              this.editGoods.winners_number = null;
              this.editGoods.head_win = 0;
              this.editGoods.free_scale = null;
            }
            this.activity_price = data.activity_goods[0].activity_goods_sku[0].price / 1000;
            this.editCheckedGoods = data.activity_goods[0].goods;
            this.isEditSpell = true;
            const selectedSku = [];
            data.activity_goods[0].activity_goods_sku.every((val, idx, array) => {
              selectedSku.push(val.goods_sku_id);
              return true;
            });
            this.goodsSku.every((val, idx, array) => {
              data.activity_goods[0].activity_goods_sku.every((val1, idx1, array1) => {
                if (val1.goods_sku_id === val.id) {
                  val.selected = true;
                  val.activity_goods_sku_id = val1.id;
                  return false;
                }
                return true;
              });
              return true;
            });
          }
        );
      });
  }

  // 提交编辑
  editSpellSubmit() {
    this.canClick = false;
    this.editGoods.free_scale = this.editGoods.free_scale / 1000;
    if (this.status === '未开始') {
      this.editActivityGoods();
    } else {
      const data = {applet_uuid: this.applet_uuid, id: this.editSpell.id, end_date: this.editSpell.end_date};
      this.ordinarySpellService.postChangeTime(data).subscribe(
        res => {
          this.canClick = true;
          if (res.code === 2000) {
            this.type = 'success';
            this.message = '修改成功';
            this.isShow = true;
            this.getActivityList(1, this.itemsPerPage, this.applet_uuid, this.status);
            this.isEditSpell = false;
          } else {
            this.type = 'error';
            this.message = res.message;
            this.isShow = true;
          }
        }
      );
    }
  }

  // 编辑活动
  editActivity() {
    this.ordinarySpellService.postEditActivity(this.editSpell).subscribe(
      res => {
        if (res.code === 2000) {
          this.canClick = true;
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.isEditSpell = false;
          this.getActivityList(1, this.itemsPerPage, this.applet_uuid, this.status);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 编辑商品
  editActivityGoods() {
    const sku_info = [];
    this.goodsSku.every((val, idx, array) => {
      if (!!val.selected) {
        sku_info.push({id: this.editGoods.id, sku_id: val.id, name: val.name, number: val.in_stock, price: this.activity_price});
        return true;
      }
      return true;
    });
    if (!sku_info.length) {
      this.type = 'info';
      this.message = '请选择商品规格';
      this.isShow = true;
      this.canClick = true;
      return;
    } else {
      this.editGoods.sku_info = JSON.stringify(sku_info);
    }
    this.ordinarySpellService.postEditGoods(this.editGoods).subscribe(
      res => {
        if (res.code === 2000) {
          this.canClick = true;
          this.editActivity();
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 删除拼团
  delSpell(id) {
    this.operateId = id;
    this.delModal.show();
  }

  submitDelActivity() {
    this.ordinarySpellService.delActivity(this.applet_uuid, this.operateId).subscribe(
      res => {
        if (res.code === 2000) {
          this.delModal.hide();
          this.getActivityList(1, this.itemsPerPage, this.applet_uuid, this.status);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }

  // 修改活动状态
  changeStatus(data) {
    this.activityStatus = data.status;
    this.operateId = data.id;
   this.changeStatusModal.show();
  }
  confirmChangeStatus() {
    const status = (this.activityStatus === '正常' ? '暂停' : '正常');
    this.ordinarySpellService.postActivityStatus(this.applet_uuid, this.operateId, status).subscribe(
      res => {
        if (res.code === 2000) {
          this.type = 'success';
          this.message = '修改成功';
          this.isShow = true;
          this.changeStatusModal.hide();
          this.getActivityList(1, this.itemsPerPage, this.applet_uuid, this.status);
        } else {
          this.type = 'error';
          this.message = res.message;
          this.isShow = true;
        }
      }
    );
  }


  // 重新开团
  createSpellAgain(data) {
    this.checkedGood = {};
    this.status = '新建拼团';
    this.createSpell.applet_uuid = data.applet_uuid;
    this.createSpell.name = data.name;
    this.createSpell.status = data.status;
    this.createSpell.description = data.description;
    this.createSpell.periods = data.periods;
    this.addActivityGoods.goods_id = data.activity_goods[0].goods_id;
    this.addActivityGoods.goods_sku = data.activity_goods[0].goods_sku;
    this.addActivityGoods.number = data.activity_goods[0].number;
    this.addActivityGoods.round = data.activity_goods[0].round;
    this.addActivityGoods.new_open_group = data.activity_goods[0].new_open_group;
    this.addActivityGoods.new_offer = data.activity_goods[0].new_offer;
    if (!!data.activity_goods[0].winners_number) {
      this.random_free = true;
      this.addActivityGoods.winners_number = data.activity_goods[0].winners_number;
      this.addActivityGoods.head_win = data.activity_goods[0].head_win;
      this.addActivityGoods.free_scale = data.activity_goods[0].free_scale;
    } else {
      this.random_free = false;
      this.addActivityGoods.winners_number = null;
      this.addActivityGoods.head_win = 0;
      this.free_scale = 100;
    }
    this.checkedGood['name'] = data.activity_goods[0].goods_name;
    this.checkedGood['first_picture'] = data.activity_goods[0].goods.first_picture;
    this.getGoodsSkuList(this.addActivityGoods.goods_id);
    // this.createSpellModal.show();
  }

  checkedNew(container) {
    if (this.addActivityGoods[container] === 0) {
      this.addActivityGoods[container] = 1;
    } else {
      this.addActivityGoods[container] = 0;
    }
  }
}
